package com.test.thread;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * implement a list, have two method, "add", "size", have two thread, thread A add 10 object to list,
 * thread B count the object in list, when the object size is 5, thread B have a message and all over
 */
public class Taobao_interview {
    volatile ArrayList<Object> list = new ArrayList<>();

    public void add(Object obj) {
        list.add(obj);
    }

    public int size() {
        return list.size();
    }

    public static void main(String[] args) {
        Taobao_interview container = new Taobao_interview();
        Object obj = new Object();
        new Thread(() -> {
            synchronized(obj) {
                System.out.println("thread B start");
                if (container.size() != 5) {
                    try {
                        obj.wait();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                System.out.println("get 5, thread B over");
                obj.notify();
            }
        }, "thread B").start();

        new Thread(() -> {
            synchronized(obj) {
                System.out.println("thread A start");
                for (int i = 0; i < 10; i++) {
                    container.add(new Object());
                    System.out.println("add object" + i);
                    if (container.size() == 5) {
                        obj.notify();
                        try {
                            obj.wait();
                        }catch(InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                    try {
                        TimeUnit.SECONDS.sleep(1);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
            System.out.println("thread A over");
        }, "thread A").start();
    }
}
